<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>One to Many - Join Table</title>
</head>
<body>
    <h3>One To Many - Using Join Table</h3>
    As mentioned in <em><q>One to Many -> Foreign Key</q></em> topic, the JPA specification does not support
    Unidirectional One to Many association where <q>One</q> side is the owning side. But there is one way
    of achieving it using a join table. Taking the same example from <em><q>One to Many -> Foreign Key</q></em> topic,
    that of Department and Employee, the Department entity maintains a collection of Employees and maps it using
    <em>@OneToMany</em> annotation to a join table as shown below -
    <pre class="brush: java">
@OneToMany
@JoinTable(name = "otm_jointable_dept_emp",
    joinColumns = @JoinColumn(name = "dept_id"),
    inverseJoinColumns = @JoinColumn(name = "emp_id"))
public Set&lt;Employee&gt; getEmployees() {
  return employees;
}      
    </pre>
    The join table maintains two foreign keys, one to table for Department entity and the other to table for
    Employee entity. The names of the columns are provided using <em>@JoinColumn</em>  annotation. The <em>joinColumns</em>
    attribute of the <em>@JoinTable</em> annotation refers to the primary key of the owning entity i.e. Department in this
    example, while the <em>inverseJoinColumns</em> attribute refers to primary key of inverse side i.e. Employee entity.
    The primary key for the join table is composite key made up of the two foreign keys.
</body>
</html>
